<?php
require_once(_PS_MODULE_DIR_.'prestatheme/controllers/admin/AdminPrestathemeEditorController.php');
require_once(_PS_MODULE_DIR_.'prestatheme/controllers/admin/AdminDefaultStyleController.php');
require_once(_PS_MODULE_DIR_.'prestatheme/models/ConfigOption.php');

class AdminConfigOptionController extends ModuleAdminController
{
    protected $configItem;
    
	public function __construct()
	{
		$this->table      = 'pt_config_option';
		$this->identifier = 'id_option';
		$this->className  = 'configOption';
		$this->lang       = true;
		
		$this->context = Context::getContext();
		
		$this->addRowAction('view');
		$this->addRowAction('edit');
		$this->addRowAction('delete');
		
		$this->bulk_actions = array(
			'delete' => array(
				'text' => $this->l('Delete selected'), 
				'confirm' => $this->l('Delete selected items?')
			)
		);

		$this->_select = '
		    CONCAT(c.`code`, \' \', c.`version`) AS `editor`,
            tl.label AS `tab_label`, il.label AS `item_label`';

		$this->_join = '
    		LEFT JOIN `'._DB_PREFIX_.'pt_config_item` i ON (i.`id_item` = a.`id_item`)
    		LEFT JOIN `'._DB_PREFIX_.'pt_config_item_lang` il ON (a.`id_item` = il.`id_item` AND il.`id_lang` = '.(int)$this->context->language->id.')
    		LEFT JOIN `'._DB_PREFIX_.'pt_config_tab` t ON (t.`id_tab` = i.`id_tab`)
    		LEFT JOIN `'._DB_PREFIX_.'pt_config_tab_lang` tl ON (t.`id_tab` = tl.`id_tab` AND tl.`id_lang` = '.(int)$this->context->language->id.')
    		LEFT JOIN `'._DB_PREFIX_.'pt_theme_editor` e ON (e.`id_editor` = t.`id_editor`)
    		LEFT JOIN `'._DB_PREFIX_.'pt_cms` c ON (c.`id_cms` = e.`id_cms`)
    		LEFT JOIN `'._DB_PREFIX_.'pt_cms_lang` cl ON (c.`id_cms` = cl.`id_cms` AND cl.`id_lang` = '.(int)$this->context->language->id.')';
		
		$this->fields_list = array(
			'id_option' => array(
				'title' => $this->l('ID'), 
				'align' => 'center', 
				'width' => 25
			),
			'label' => array(
				'title' => $this->l('Option name'), 
				'align' => 'center', 
                'callback' 	=> 'getOptionName'
			),
			'item_label' => array(
				'title' => $this->l('Item name'), 
				'align' => 'center', 
			),
			'tab_label' => array(
				'title' => $this->l('Tab name'), 
				'align' => 'center', 
			),
			'editor' => array(
				'title' => $this->l('Target CMS'), 
				'align' => 'center', 
			),
            'position' => array(
                'title' => $this->l('Position'),
                'width' => 40,
                'filter_key' => 'position',
                'align' => 'center',
                'position' => 'position'
            ),
            'date_add' => array(
                'title' 	=> $this->l('Created On'),
                'type' 	=> 'date'
            ),
            'date_upd' => array(
                'title' 	=> $this->l('Last update On'),
                'type' 	=> 'date'
            ),
			'active' => array(
				'title' => $this->l('Enabled'), 
				'width' => 25, 
				'align' => 'center', 
				'active' => 'status', 
				'type' => 'bool', 
				'orderby' => false
			),
		);

		$this->configItem = AdminPrestathemeEditorController::getCurrentItem();
        if (!empty($this->configItem->id))
            $this->_filter = 'AND a.`id_item` = '.(int)$this->configItem->id;
        
		parent::__construct();
	}
    
    public function setIdItemForFilter ($id_item) {
        $this->_filter = 'AND a.`id_item` = '.(int)$id_item;
    }
    
    public function getOptionName ($echo, $row)
    {
        if (empty($row['label']))
            return '';
        elseif (empty($row['id_parent']))
            return $row['label'];
        $sql = '
            SELECT id_parent, label, id_option
            FROM `' . _DB_PREFIX_ . 'pt_config_option` o
            LEFT JOIN `'._DB_PREFIX_.'pt_config_option_lang` ol ON (o.`id_option` = ol.`id_opion` AND ol.`id_lang` = '.(int)$this->context->language->id.')
            WHERE `id_option` = '. $row['id_parent'];
        $new_row = Db :: getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql);
        return $this->getOptionName($echo, $new_row) .' '. $row['label'];
    }

	/**
	 * Modifying initial getList method to display position feature (drag and drop)
	 */
	public function getList($id_lang, $order_by = null, $order_way = null, $start = 0, $limit = null, $id_lang_shop = false)
	{
		if ($order_by && $this->context->cookie->__get($this->table.'Orderby'))
			$order_by = $this->context->cookie->__get($this->table.'Orderby');
		else
			$order_by = 'position';

		parent::getList($id_lang, $order_by, $order_way, $start, $limit, $id_lang_shop);
	}
	
	public function renderForm()
	{
		$this->fields_form = array(
			'tinymce' => true,
			'legend' => array(
				'title' => $this->l('Available CMS for prestatheme'),
				'image' => '../img/admin/cog.gif'
			),
			'input' => array(
				array(
					'type' => 'text',
					'label' => $this->l('CSS Style'),
					'name' => 'selector',
					'required' => true,
					'size' => 63,
                    'id' => 'cssstyle_autocomplete_input',
					'desc' => $this->l('Select the associated tab if parent item will not set')
				),
				array(
					'type' => 'hidden',
					'name' => 'id_style',
                    'id'   => 'pt_id_style',
					'required' => true,
				),
				array(
					'type' => 'textarea',
					'label' => $this->l('Default CSS Style'),
					'name' => 'style',
                    'id'   => 'pt_style',
					'rows' => 2,
					'cols' => 60,
					'hint' => $this->l('Only CSS script (attribute:value; attribute:value; ...)'),
					'desc' => $this->l('The default CSS Style for the current CSS selector'),
				),
				array(
					'type' => 'text',
					'label' => $this->l('Name'),
					'name' => 'name',
					'size' => 63,
					'required' => true,
					'hint' => $this->l('Invalid characters:').' <>;=#{}'
				),
				array(
					'type' => 'text',
					'label' => $this->l('Label'),
					'name' => 'label',
					'size' => 63,
					'lang' => true,
					'desc' => $this->l('The label in the editor interface.'),
				),
				array(
					'type' => 'select',
					'label' => $this->l('Item'),
					'name' => 'id_item',
					'required' => true,
					'options' => array(
						'query' => ConfigItem::getConfigItems(true/*, ' AND t.`id_editor` = '*/),
						'id' => 'id_item',
						'name' => 'fullname',
					),
					'desc' => $this->l('Select the associated item')
				),
				array(
					'type' => 'select',
					'label' => $this->l('Type'),
					'name' => 'type',
					'required' => true,
					'options' => array(
						'query' => array(
                                    array('value'=> 'DES-Columns', 'label'=> $this->l('Columns settings ([Center], [Left|Center], [Center|Right], [Left|Center|Right], [Center|Left|Right])')),
                                    //array('value'=> 'DES-column', 'label'=> $this->l('Column structure')),
                                    array('value'=> 'DES-SelectedDesign', 'label'=> $this->l('From available design (Macro design)')),
                                    array('value'=> 'DES-ActiveShadow', 'label'=> $this->l('Active/deactive shadow design (On, Off)')),
                                    array('value'=> 'DES-Shadow', 'label'=> $this->l('Shadow design (Left, Bottom, Blur, Rayon, Color)')),
                                    array('value'=> 'DES-ActiveRadius', 'label'=> $this->l('Active/deactive raduis design (On, Off)')),
                                    array('value'=> 'DES-Radius', 'label'=> $this->l('Raduis design (Top left, Top right, Bottom right, Bottom left)')),
                                    array('value'=> 'DES-ListDesign', 'label'=> $this->l('List design (Many per line, One per line)')),
                                    
                                    array('value'=> 'CSS-Dim', 'label'=> $this->l('Dimension (Value[Int,Float]+unit[px,pt,%,em,...])')),
                                    array('value'=> 'CSS-TopRightBottomLeft', 'label'=> $this->l('Dimensions (Top, Right, Bottom, Left)')),
                                    array('value'=> 'CSS-BoxDim', 'label'=> $this->l('Box dimensions (Width x Height)')),
                                    array('value'=> 'CSS-Color', 'label'=> $this->l('Color (Color picker)')),
                                    array('value'=> 'CSS-Text', 'label'=> $this->l('Text style (font, color, align, etc...)')),
                                    array('value'=> 'CSS-Link', 'label'=> $this->l('Link style (font, color, align, etc...)')),
                                    array('value'=> 'CSS-Image', 'label'=> $this->l('Image design')),
                                    array('value'=> 'CSS-Background', 'label'=> $this->l('Background desgin (Color, image, position, etc...)')),
                                    array('value'=> 'CSS-Border', 'label'=> $this->l('Border design (Size, Style, Color, for each top, right, bottom and left side)')),
                                    array('value'=> 'CSS-Block', 'label'=> $this->l('Block design (Box dimensions, background, shadow, radius)')),
                                    array('value'=> 'CSS-Other', 'label'=> $this->l('Default design (Attribute:Value)')),
                                ),
						'id' => 'value',
						'name' => 'label',
					),
					'desc' => $this->l('Choose the type')
				),
				array(
					'type' => 'textarea',
					'label' => $this->l('Description'),
					'name' => 'description',
					'lang' => true,
					'rows' => 5,
					'cols' => 60,
					'hint' => $this->l('Forbidden characters:').' <>;=#{}',
					'desc' => $this->l('Describe the impact of the option on the theme.'),
				),
				array(
					'type' => 'radio',
					'label' => $this->l('Available'),
					'name' => 'active',
					'required' => false,
					'class' => 't',
					'is_bool' => true,
					'values' => array(
						array(
							'id' => 'active_on',
							'value' => 1,
							'label' => $this->l('Enabled')
						),
						array(
							'id' => 'active_off',
							'value' => 0,
							'label' => $this->l('Disabled')
						)
					),
				),
				array(
					'type' => 'text',
					'label' => $this->l('Iso Lang'),
					'name' => 'lang_iso',
					'size' => 2,
					'readonly' => true,
					'required' => true,
					'lang' => true,
					'desc' => $this->l('This field is authomaticaly fill.'),
				),
			),
			'submit' => array(
				'title' => $this->l('   Save   '),
				'class' => 'button'
			)
		);
        $languages = Language::getLanguages(false);
        $this->fields_value['lang_iso'] = array();
        foreach ($languages AS $lang)
        {
            $this->fields_value['lang_iso'][$lang['id_lang']] = $lang['iso_code'];
        }

		if (!($obj = $this->loadObject(true)))
			return;
        $output = "
        <script type='text/javascript'> 
        $(document).ready(function (){
            $('#cssstyle_autocomplete_input')
                .autocomplete('ajax_prestatheme_css_style.php', {
                    minChars: 1,
                    autoFill: true,
                    max:20,
                    matchContains: true,
                    mustMatch:true,
                    scroll:false,
                    cacheLength:0,
                    formatItem: function(item) {
                        return item[1]+' - '+item[0];
                    }
                }).result(function (event, data, formatted) {
                    if (data == null)
                        return false;
                    var id_style = data[1];
                    var selector = data[0]; 
                    var style    = data[2]; 
                    $('#id_style').val(id_style);
                    $('#pt_style').val(style);
                });
            
            $('#cssstyle_autocomplete_input').setOptions({
                extraParams: {
                    excludeIds : ''
                }
            });
        }); 
        </script>
        ";
		return $output.parent::renderForm();
	}
    
    public function postProcess()
    {
        // Save edition of default style
        if (Tools::isSubmit('submitAddpt_config_option') || Tools::isSubmit('submitAddpt_config_optionAndStay') || 
            Tools::isSubmit('updatept_config_option') || Tools::isSubmit('addpt_config_option')) {
            
            // Remove (cms: ****) from selector
            if($pos = strpos($_POST['selector'], ' (cms:'))
            	$_POST['selector'] = substr($_POST['selector'], 0, $pos);
            
            $submitted = $_POST;
            $_POST = array(
                'id_style' => $submitted['id_style'],
                'id_cms'   => ConfigItem::getIdCmsByIdItem($submitted['id_item']),
                'selector' => $submitted['selector'],
                'style'    => $submitted['style'],
                'active'   => 1,
                'submitAddpt_default_style' => 1,
                'updatept_default_style'    => 1,
            );
            $this->admin_default_style = new AdminDefaultStyleController();
            $this->admin_default_style->redirect_after = false;
			$this->admin_default_style->initProcess();
			$this->admin_default_style->postProcess();
            
            $_POST = $submitted;
            $_POST['id_style'] = $this->admin_default_style->object->id;
        }
        parent::postProcess();
    }

	public function renderView()
	{
		if (!($object = $this->loadObject()))
			return;
			
		$this->tpl_view_vars = array(
			'id_lang' => Context::getContext()->language->id,
			'object' => $object,
			'head_title' => ($object->id ? $object->getCMSName() : $this->l('New CMS to be avaible on Prestatheme')),
			'shopContext' => Shop::getContext(),
		);

		return parent::renderView();
	}
    
    public function genNamespace ($id_item) {
        $namespace = '';
        $currentId = $id_item;
        $currentEltType = 'item';
        while (!empty($currentId)) {
            if ($currentEltType == 'item') {
                $sql = 'SELECT `name`,`id_tab`,`id_parent` FROM `'. _DB_PREFIX_ .'pt_config_item` WHERE `id_item` = '. (int)$currentId;
                $currentElt = Db::getInstance()->getRow($sql);
                if (!empty($currentElt['name'])) {
                    $namespace = $currentElt['name'] .'/'.$namespace;
                    if (!empty($currentElt['id_tab'])) {
                        $currentEltType = 'tab';
                        $currentId = $currentElt['id_tab'];
                    } elseif (!empty($currentElt['id_parent'])) {
                        $currentId = $currentElt['id_parent'];
                    }
                }
                else {
                    $currentId = false;
                }
            } elseif ($currentEltType == 'tab') {
                $sql = 'SELECT `name`,`id_editor` FROM `'. _DB_PREFIX_ .'pt_config_tab` WHERE `id_tab` = '. (int)$currentId;
                $currentElt = Db::getInstance()->getRow($sql);
                if (!empty($currentElt['name'])) {
                    $namespace = $currentElt['name'] .'/'. $namespace;
                    if (!empty($currentElt['id_editor'])) {
                        $currentEltType = 'editor';
                        $currentId = $currentElt['id_editor'];
                    }
                }
                else {
                    $currentId = false;
                }
            } elseif ($currentEltType == 'editor') {
                $sql = 'SELECT CONCAT(c.`code`, c.`version`) AS `name`
                        FROM `'. _DB_PREFIX_ .'pt_theme_editor` e
                        LEFT JOIN `' . _DB_PREFIX_ . 'pt_cms` c ON (e.`id_cms` = c.`id_cms`)
                        WHERE `id_editor` = '. (int)$currentId;
                $currentElt = Db::getInstance()->getRow($sql);
                if (!empty($currentElt['name'])) {
                    $namespace = $currentElt['name'] .'/'. $namespace;
                    if (!empty($currentElt['id_editor'])) {
                        $currentEltType = 'editor';
                        $currentId = $currentElt['id_editor'];
                    }
                }
                $currentId = false;
            } else return false;
        }
        return $namespace;
    }
}